package com.education.ai.dao.impl;

import com.education.ai.dao.TeachingPlanDao;
import com.education.ai.entity.TeachingPlan;
import com.education.ai.util.JdbcUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.*;

/**
 * 教学计划数据访问实现类
 */
@Repository
public class TeachingPlanDaoImpl implements TeachingPlanDao {

    private static final Logger logger = LoggerFactory.getLogger(TeachingPlanDaoImpl.class);

    @Autowired
    private JdbcUtil jdbcUtil;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public TeachingPlan save(TeachingPlan plan) {
        if (plan.getId() == null) {
            // 插入操作
            String sql = "INSERT INTO teaching_plans (title, content, subject, grade, teacher_id, " +
                    "duration, is_template, objectives, activities, resources, assessment, " +
                    "create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            // 设置创建和更新时间
            Date now = new Date();
            if (plan.getCreateTime() == null) {
                plan.setCreateTime(now);
            }
            if (plan.getUpdateTime() == null) {
                plan.setUpdateTime(now);
            }

            long id = jdbcUtil.executeInsert(sql,
                    plan.getTitle(),
                    plan.getContent(),
                    plan.getSubject(),
                    plan.getGrade(),
                    plan.getTeacherId(),
                    plan.getDuration(),
                    plan.getIsTemplate(),
                    plan.getObjectives(),
                    plan.getActivities(),
                    plan.getResources(),
                    plan.getAssessment(),
                    new Timestamp(plan.getCreateTime().getTime()),
                    new Timestamp(plan.getUpdateTime().getTime()));

            plan.setId(id);
            return plan;
        } else {
            // 更新操作
            String sql = "UPDATE teaching_plans SET title = ?, content = ?, subject = ?, grade = ?, " +
                    "teacher_id = ?, duration = ?, is_template = ?, objectives = ?, activities = ?, " +
                    "resources = ?, assessment = ?, update_time = ? WHERE id = ?";

            // 设置更新时间
            plan.setUpdateTime(new Date());

            jdbcUtil.executeUpdate(sql,
                    plan.getTitle(),
                    plan.getContent(),
                    plan.getSubject(),
                    plan.getGrade(),
                    plan.getTeacherId(),
                    plan.getDuration(),
                    plan.getIsTemplate(),
                    plan.getObjectives(),
                    plan.getActivities(),
                    plan.getResources(),
                    plan.getAssessment(),
                    new Timestamp(plan.getUpdateTime().getTime()),
                    plan.getId());

            return plan;
        }
    }

    @Override
    public Optional<TeachingPlan> findById(Long id) {
        String sql = "SELECT * FROM teaching_plans WHERE id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, id);
        return results.isEmpty() ? Optional.empty() : Optional.of(mapRowToTeachingPlan(results.get(0)));
    }

    @Override
    public List<TeachingPlan> findAll() {
        String sql = "SELECT * FROM teaching_plans";
        return mapResultsToTeachingPlans(jdbcUtil.executeQuery(sql));
    }

    @Override
    public List<TeachingPlan> findByTeacherId(String teacherId) {
        String sql = "SELECT * FROM teaching_plans WHERE teacher_id = ? ORDER BY create_time DESC";
        return mapResultsToTeachingPlans(jdbcUtil.executeQuery(sql, teacherId));
    }

    @Override
    public List<TeachingPlan> findBySubject(String subject) {
        String sql = "SELECT * FROM teaching_plans WHERE subject = ?";
        return mapResultsToTeachingPlans(jdbcUtil.executeQuery(sql, subject));
    }

    @Override
    public List<TeachingPlan> findByGrade(String grade) {
        String sql = "SELECT * FROM teaching_plans WHERE grade = ?";
        return mapResultsToTeachingPlans(jdbcUtil.executeQuery(sql, grade));
    }

    @Override
    public List<TeachingPlan> findByTopic(String topic) {
        // 由于数据库可能没有topic字段，这里使用title字段代替
        String sql = "SELECT * FROM teaching_plans WHERE title LIKE ?";
        return mapResultsToTeachingPlans(jdbcUtil.executeQuery(sql, "%" + topic + "%"));
    }

    @Override
    public boolean deleteById(Long id) {
        String sql = "DELETE FROM teaching_plans WHERE id = ?";
        int rows = jdbcUtil.executeUpdate(sql, id);
        return rows > 0;
    }

    @Override
    public long count() {
        String sql = "SELECT COUNT(*) AS count FROM teaching_plans";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql);
        if (!results.isEmpty()) {
            return ((Number) results.get(0).get("count")).longValue();
        }
        return 0;
    }

    /**
     * 将查询结果映射为教学计划对象列表
     */
    private List<TeachingPlan> mapResultsToTeachingPlans(List<Map<String, Object>> results) {
        List<TeachingPlan> plans = new ArrayList<>();
        for (Map<String, Object> row : results) {
            plans.add(mapRowToTeachingPlan(row));
        }
        return plans;
    }

    /**
     * 将单行结果映射为教学计划对象
     */
    private TeachingPlan mapRowToTeachingPlan(Map<String, Object> row) {
        TeachingPlan plan = new TeachingPlan();

        plan.setId(((Number) row.get("id")).longValue());
        plan.setTitle((String) row.get("title"));
        plan.setContent((String) row.get("content"));
        plan.setSubject((String) row.get("subject"));
        plan.setGrade((String) row.get("grade"));
        plan.setTeacherId((String) row.get("teacher_id"));

        if (row.get("duration") != null) {
            plan.setDuration(((Number) row.get("duration")).intValue());
        }

        if (row.get("is_template") != null) {
            plan.setIsTemplate((Boolean) row.get("is_template"));
        }

        plan.setObjectives((String) row.get("objectives"));
        plan.setActivities((String) row.get("activities"));
        plan.setResources((String) row.get("resources"));
        plan.setAssessment((String) row.get("assessment"));

        if (row.get("create_time") != null) {
            Object createTimeObj = row.get("create_time");
            if (createTimeObj instanceof Timestamp) {
                plan.setCreateTime(new Date(((Timestamp) createTimeObj).getTime()));
            } else if (createTimeObj instanceof java.time.LocalDateTime) {
                java.time.LocalDateTime localDateTime = (java.time.LocalDateTime) createTimeObj;
                plan.setCreateTime(java.sql.Timestamp.valueOf(localDateTime));
            } else if (createTimeObj instanceof Date) {
                plan.setCreateTime((Date) createTimeObj);
            } else {
                logger.warn("未知的创建时间类型: {} - {}", createTimeObj.getClass().getName(), createTimeObj);
                // 尝试转换为字符串然后解析
                try {
                    plan.setCreateTime(java.sql.Timestamp.valueOf(createTimeObj.toString()));
                } catch (Exception e) {
                    logger.error("无法解析创建时间: " + createTimeObj, e);
                    plan.setCreateTime(new Date()); // 使用当前时间作为后备
                }
            }
        }

        if (row.get("update_time") != null) {
            Object updateTimeObj = row.get("update_time");
            if (updateTimeObj instanceof Timestamp) {
                plan.setUpdateTime(new Date(((Timestamp) updateTimeObj).getTime()));
            } else if (updateTimeObj instanceof java.time.LocalDateTime) {
                java.time.LocalDateTime localDateTime = (java.time.LocalDateTime) updateTimeObj;
                plan.setUpdateTime(java.sql.Timestamp.valueOf(localDateTime));
            } else if (updateTimeObj instanceof Date) {
                plan.setUpdateTime((Date) updateTimeObj);
            } else {
                logger.warn("未知的更新时间类型: {} - {}", updateTimeObj.getClass().getName(), updateTimeObj);
                // 尝试转换为字符串然后解析
                try {
                    plan.setUpdateTime(java.sql.Timestamp.valueOf(updateTimeObj.toString()));
                } catch (Exception e) {
                    logger.error("无法解析更新时间: " + updateTimeObj, e);
                    plan.setUpdateTime(new Date()); // 使用当前时间作为后备
                }
            }
        }

        return plan;
    }
} 